#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# message_logger.py
#
#  Copyright (c) 2007 INdT (Instituto Nokia de Technologia)
#                2007 Kenneth Christiansen
#
#  Author: Kenneth Rohde Christiansen <kenneth.christiansen@gmail.com>
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License as
#  published by the Free Software Foundation; either version 2 of the
#  License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
#  USA

import os
import datetime
from xml.etree import ElementTree

class MessageLogger(object):
    """
    A class for logging chat conversations.
    """

    def __init__(self, contact_id):
        """
        Constructor.
        """

        self.contact_id = contact_id
        self.log_filename = None
        self.log_tag = None


    def create_or_open(self):
        """
        Functions that creates a log file or opens it if it already
        exists.
        """

        log_dir = os.path.join(os.path.expanduser(os.environ.get('HOME')), '.ereseva', 'logs')

        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

        user_log_dir = os.path.join(log_dir, self.contact_id)

        if not os.path.exists(user_log_dir):
            os.makedirs(user_log_dir)

        date = datetime.date.today().isoformat().replace("-", "")

        self.log_filename = os.path.join(user_log_dir, date + ".log")

        if os.path.exists(self.log_filename):
            tree = ElementTree.parse(self.log_filename)
            self.log_tag = tree.getroot()
        else:
            self.log_tag = ElementTree.Element("log")


    def close(self):
        """
        Function that closes the log file.
        """

        if self.log_tag != None and self.log_filename != None:
            tree = ElementTree.ElementTree(self.log_tag)
            tree.write(self.log_filename, 'UTF-8')


    def log_message(self, timestamp, contact_id, alias, message, received):
        """
        Functions that logs a message.
        """

        message_tag = ElementTree.SubElement(self.log_tag, "message")
        message_tag.set("time", timestamp)

        if received:
            message_tag.set("from", contact_id)
        else:
            message_tag.set("to", contact_id)

        message_tag.set("nick", alias)
        message_tag.text = message

